package com.chap15;

import sun.misc.Contended;

/**
 * <p>
 * <code>FalseSharingTest</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-04-18 13:59
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
public class FalseSharingTest2 {

    public static void main(String[] args) throws InterruptedException {
        testPointer(new Pointer());
    }

    private static void testPointer(Pointer pointer) throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 100000000; i++) {
                pointer.x++;
            }
        });

        Thread t2 = new Thread(()->{
            for (int i = 0; i < 100000000; i++) {
                pointer.y++;
            }
        });

        //单线程操作自己的变量，没有线程安全问题
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(pointer.x+":"+pointer.y);
        System.out.println(System.currentTimeMillis()-start);

    }

    private static class Pointer{
        @Contended
        volatile long x;
        volatile long y;
    }
}
